//
//  BYScanStyle.swift
//  BYScan
//
//  Created by yetupal on 2023/6/28.
//

import UIKit
import AVFoundation

// 计算配置
class BYScanStyle {
    
    
    static let defaultServie = BYScanStyle()
    
    // 扫描区域
    private var scanning_w: CGFloat = 240
    private var scanning_h: CGFloat = 240
    
    // 矩形框(视频显示透明区)域向上移动偏移量，0表示扫码透明区域在当前视图中心位置，如果负值表示扫码区域下移
    var centerUpOffset: CGFloat = 44 + 100
    
    // 边界线颜色
    var lineColor: UIColor = UIColor.white
    // 四个角颜色
    var hornColor: UIColor = UIColor.red
    // 非识别区域
    var coverColor: UIColor = UIColor.black.withAlphaComponent(0.382)
    
    // 是否只识别条形码 true 条形码 false 二维码
    var isWhetherBarCode: Bool = false

    // 扫描区域
    func scanningArea() -> CGRect {
        if isWhetherBarCode {
            scanning_w = 280
            scanning_h = 128
        } else {
            scanning_w = 240
            scanning_h = 240
        }
        
        let fx: CGFloat =  UIScreen.main.bounds.width - scanning_w
        let fy: CGFloat =  UIScreen.main.bounds.height - scanning_h - self.centerUpOffset
        return CGRect.init(x: fx / 2, y: fy / 2, width: scanning_w, height: scanning_h)
    }
    
    
    // 条形码、二维码
    func allowedTypes() -> [AVMetadataObject.ObjectType] {
        var rspList = [AVMetadataObject.ObjectType.upce,
                 AVMetadataObject.ObjectType.code39,
                 AVMetadataObject.ObjectType.code39Mod43,
                 AVMetadataObject.ObjectType.ean13,
                 AVMetadataObject.ObjectType.ean8,
                 AVMetadataObject.ObjectType.code93,
                 AVMetadataObject.ObjectType.code128,
                 AVMetadataObject.ObjectType.pdf417,
                 AVMetadataObject.ObjectType.aztec]
        
        if !isWhetherBarCode {
            rspList.append(AVMetadataObject.ObjectType.qr)
        }
        return rspList
    }
}


// 扩展导航样式
extension UINavigationBar {
    
    /// 夜间黑暗
    func night_black() {
        self.isTranslucent = false
        self.shadowImage = UIImage()
        self.tintColor = UIColor.white
        self.barTintColor = UIColor.black
        self.setBackgroundImage(nil, for: .default)
        self.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 18), .foregroundColor: UIColor.white]
        
        // 兼容iOS15
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.shadowImage = UIImage()
            appearance.shadowColor = UIColor.clear
            appearance.backgroundColor = UIColor.black
            appearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 18), .foregroundColor: UIColor.white]
            self.standardAppearance = appearance;
            self.scrollEdgeAppearance = appearance
        }
    }
}
